package model

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/go-redis/redis/v7"
)

var (
	userTable = "users"
)

//UserMgr 用户管理，就是通过检查redis数据表中的数据
type UserMgr struct {
	client *redis.Client
}

//NewUserMgr 初始化UsserMgr
func NewUserMgr() (mgr *UserMgr) {

	mgr = &UserMgr{
		client: redis.NewClient(&redis.Options{
			Addr:     "127.0.0.1:6379",
			Password: "", // no password set
			DB:       0,  // use 默认
		}),
	}
	_, err := mgr.client.Ping().Result()
	if err != nil {
		fmt.Println(err)
	}

	return
}

func (mgr *UserMgr) getUser(id int) (user *User, err error) {
	result, err := mgr.client.HGet(userTable, string(id)).Result()
	if err != nil {
		err = ErrUserNoExist
		return
	}

	user = &User{}
	err = json.Unmarshal([]byte(result), user)
	if err != nil {
		return
	}
	return

}

//Login 处理登录相关Redis操作
func (mgr *UserMgr) Login(id int, passwd string) (user *User, err error) {
	user, err = mgr.getUser(id)
	if err != nil {
		return
	}

	if user.UserID != id || user.Passwd != passwd {
		err = ErrInvalidPasswd
		return
	}

	user.Status = UserStatusOnline
	user.LastLogin = fmt.Sprintf("%v", time.Now())

	return
}

//Register 处理注册相关Redis操作
func (mgr *UserMgr) Register(user *User) (err error) {
	if user == nil {
		fmt.Println("invalid user")
		err = ErrInvalidParams
		return
	}

	_, err = mgr.getUser(user.UserID)
	if err == nil {
		err = ErrUserExist
		return
	}

	if err != ErrUserNoExist {
		return
	}

	data, err := json.Marshal(user)
	if err != nil {
		return
	}

	mgr.client.HSet(userTable, string(user.UserID), data)
	return
}
